#!/bin/bash

if [ $# = 1 ]
then
    configScript=$1
else
    echo No configure script path passed in!!!
    exit
fi

if [ -f $configScript ]
then
    source $configScript
else
    echo Invalid configure script path!!!
    exit
fi

# Const
implScript=InitLinuxImpl.sh

if [ -f $implScript ]
then
    source $implScript
else
    echo No $implScript in current folder!!!
    exit
fi

############################
echo Now start LAMP install!
echo

function InstallDownloadedPackage()
{
    pkg=$1
    config=$2

    echo Install $pkg

    pkgDir=$(GetConfigVar FTPDownloadDir $OS $VER)
    AssertFunctionResult
    pkgPath=${pkgDir}/$pkg
    if [ -f $pkgPath ]
    then
        pkgUnzipPath=$(ExtractFile $pkgPath $pkgDir)
        if [ $? != $SUCCESS ]
        then
            echo Extract file failed: $pkgPath
            echo
            return
        fi

        if [ -d $pkgUnzipPath ]
        then
            MakeInstallPackage $pkgUnzipPath "${config}"
        else
            echo Invalid package make install path ${pkgUnzipPath}!!!
        fi
    else
        echo No installed package path: $pkgPath!!!
    fi
    flag=$(GetConfigVar IsCheckInstall $OS $VER)
    AssertFunctionResult
    WaitForCheck $flag

    echo
}

### Download from FTP ###
flag=$(GetConfigVar IsDownloadLAMPPkg $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Download packages from FTP

    desDir=$(GetConfigVar FTPDownloadDir $OS $VER)
    AssertFunctionResult
    if [ -d $desDir ]
    then
        cd $desDir
        cmd=$(GetConfigVar FTPCmd $OS $VER)
        AssertFunctionResult
        user=$(GetConfigVar FTPLoginUser $OS $VER)
        AssertFunctionResult
        ip=$(GetConfigVar FTPIP $OS $VER)
        AssertFunctionResult

        packageList=($(GetConfigArray FTPDownloads $OS $VAR))
        for((i=0; i<${#packageList[@]}; i++))
        do
            FTPGet $cmd $user $ip ${packageList[${i}]}
        done
    else
        echo No FTP download dir: $desDir!!!
    fi

    echo
fi

### Install LAMP utilities ###
flag=$(GetConfigVar IsInstallLAMPUtilities $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo LAMP utilites from repo

    utilities=($(GetConfigArray LAMPUtilities $OS $VAR))
    AssertFunctionResult
    installApp=$(GetConfigVar InstallApp $OS $VER)
    AssertFunctionResult

    UpdateInstallAppSource $installApp

    for((i=0; i<${#utilities[@]}; i++))
    do
        InstallUtil $installApp ${utilities[${i}]}
    done

    echo
fi

### Install Apache ###
flag=$(GetConfigVar IsInstallApache $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Install Apache

    installExpat=true
    installApr=true
    installAprUtil=true
    installPcre=true
    installOpenssl=true
    installApache=true

    if [ $installExpat = true ]
    then
        InstallDownloadedPackage $expat
    fi
    if [ $installApr = true ]
    then
        InstallDownloadedPackage $apr
    fi
    if [ $installAprUtil = true ]
    then
        aprutilConfig="--with-apr=/usr/local/apr"
        InstallDownloadedPackage $aprutil $aprutilConfig
    fi
    if [ $installPcre = true ]
    then
        InstallDownloadedPackage $pcre
    fi
    if [ $installOpenssl = true ]
    then
	echo Now make install openssl
        echo !!! If there is any make error, run "make clean" and have another try !!!
        read -p "Press ENTER to continue ..." tmp
        echo
        InstallDownloadedPackage $openssl
    fi
    if [ $installApache = true ]
    then
        httpdConfig="--enable-ssl"
        InstallDownloadedPackage $httpd $httpdConfig
    fi
    echo
fi

### Install MySQL ###
flag=$(GetConfigVar IsInstallMySQL $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Install MySQL

    pkgDir=$(GetConfigVar FTPDownloadDir $OS $VER)
    AssertFunctionResult
    installApp=$(GetConfigVar InstallApp $OS $VER)
    AssertFunctionResult
    mysqlPkgName=$(GetConfigVar LAMPMySQLPkgName $OS $VER)
    AssertFunctionResult

    if [ $installApp = apt ]
    then
        mysqlSource=${pkgDir}/$mysqlaptsource
        if [ -f $mysqlSource ]
        then
            dpkg -i $mysqlSource
            $installApp update
            $installApp install $mysqlPkgName
        else
            echo $mysqlSource does not exist!!!
        fi
    else
        echo Not valid install app: $installApp !!!
    fi

    echo

    flag=$(GetConfigVar IsCheckInstall $OS $VER)
    AssertFunctionResult
    WaitForCheck $flag
fi

### Configure MySQL ###
flag=$(GetConfigVar IsConfigureMySQL $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Configure MySQL

    GetMySQLDPath
    if [ $? == $SUCCESS ]
    then
	service mysqld start

        mysqlPath=$(GetMySQLPath)
	if [ $? == $SUCCESS ]
	then
            read -p "Now try first login MySQL, but it maybe fail and just ignore it and quit anyway..." tmp
	    $mysqlPath -u root -p

            mysqlLogPath=$(GetMySQLLogPath)
	    if [ $? == $SUCCESS ]
	    then
                read -p "Now will open log file contains temperary root password, REMEMBER it to use later (the password may also be empty)..." tmp
                grep --color -nHi password $mysqlLogPath
		read -p "Now will change to new password, please input your new password (do NOT use the new one for following login, use the rememberd one (or empty)):" newpw
		echo ALTER USER "'"root"'"@"'"localhost"'" IDENTIFIED BY "'"${newpw}"'"";" | $mysqlPath -u root -p
	    else
		echo MySQL configure error: NO /var/log/mysqld.log found !!!
	    fi
	else
            echo MySQL configure error: NO /usr/bin/mysql found !!!
	fi
    else
	echo MySQL configure error: NO mysqld found !!!
    fi
    echo

    flag=$(GetConfigVar IsCheckInstall $OS $VER)
    AssertFunctionResult
    WaitForCheck $flag
fi

### Install PHP ###
flag=$(GetConfigVar IsInstallPHP $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Install PHP
    read -p "The make may be failed because of memory size limitation, reset the machien and have another try if it happens. Now press any key to continue ..." tmp
    phpConfig="--with-apxs2=/usr/local/apache2/bin/apxs --with-mysqli --disable-fileinfo"
    InstallDownloadedPackage $php $phpConfig
    echo 
fi

### Configure Python ###
flag=$(GetConfigVar IsConfigurePython $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Configure Python
    if [ ! -f /usr/bin/python ]
    then
        cd /usr/bin
        if [ -f /usr/bin/python3 ]
        then
            ln -s python3 python
        elif [ -f /usr/bin/python2 ]
        then
            ln -s python2 python
        else
            installApp=$(GetConfigVar InstallApp $OS $VER)
            AssertFunctionResult
            InstallUtil $installApp python3
            if [ ! -f /usr/bin/python ]
            then
                if [ -f /usr/bin/python3 ]
                then
                    cd /usr/bin
                    ln -s python3 python
                else
                    echo Python3 installation failed!!!
                fi
            fi
        fi
    fi
    echo
fi

### Configure Apache ###
flag=$(GetConfigVar IsConfigureApache $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Configure Apache

    pythonConfigPath=$(GetConfigVar LAMPPythonConfigPath $OS $VER)
    AssertFunctionResult
    httpdIP=$(GetConfigVar LAMPHttpdIP $OS $VER)
    AssertFunctionResult
    httpdDocs=$(GetConfigVar LAMPHttpdDocs $OS $VER)
    AssertFunctionResult

    python $pythonConfigPath $httpdConf $httpdIP $httpdPort $httpdDocs $vhostConf $sslConf
    if [ -f ${httpdConf}.modify.tmp ]
    then
        mv $httpdConf ${httpdConf}.bak
        mv ${httpdConf}.modify.tmp $httpdConf
    fi
    if [ -f ${vhostConf}.modify.tmp ]
    then
        mv $vhostConf ${vhostConf}.bak
        mv ${vhostConf}.modify.tmp $vhostConf
    fi
    if [ -f ${sslConf}.modify.tmp ]
    then
        mv $sslConf ${sslConf}.bak
        mv ${sslConf}.modify.tmp $sslConf
    fi
    if [ ! -f /usr/lib/libssl.so.1.1 ]
    then
	if [ -f /usr/local/lib/libssl.so.1.1 ]
	then
	    ln -s /usr/local/lib/libssl.so.1.1 /usr/lib/libssl.so.1.1
	fi
    fi
    if [ ! -f /usr/lib/libcrypto.so.1.1 ]
    then
	if [ -f /usr/local/lib/libcrypto.so.1.1 ]
	then
	    ln -s /usr/local/lib/libcrypto.so.1.1 /usr/lib/libcrypto.so.1.1
	fi
    fi
    if [ ! -f /usr/lib/libpcre.so.1 ]
    then
	if [ -f /usr/local/lib/libpcre.so.1 ]
	then
	    ln -s /usr/local/lib/libpcre.so.1 /usr/lib/libpcre.so.1
	fi
    fi
    if [ -d $apacheConf ]
    then
        read -p "Now configure SSL for apache..." tmp
        cd $apacheConf
        openssl genrsa -aes256 -out server.key 2048
        openssl req -sha256 -new -x509 -days 1826 -key server.key -out server.crt
    fi
    echo
fi

### Configure EJ Calendar ###
flag=$(GetConfigVar IsConfigureCalendar $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Configure EJ Calendar

    if [ -d $cronDailyPath ]
    then
        calendarCronScript=$(GetConfigVar LAMPCalendarCronScript $OS $VER)
        AssertFunctionResult
        calendarServicePath=$(GetConfigVar LAMPEJServicePath $OS $VER)
        AssertFunctionResult

        dailyScript=$cronDailyPath/$calendarCronScript
        echo \#!/bin/bash > $dailyScript
        echo if [ -d $calendarServicePath ]\; then >> $dailyScript
        echo "    "cd $calendarServicePath >> $dailyScript
        echo "    echo "\"Sart calendar handle script\" >> $dailyScript
        echo "    "if [ -f EJCalendar.py ]\; then >> $dailyScript
        echo "        "python EJCalendar.py >> $dailyScript
        echo "    "fi >> $dailyScript
        echo "    echo "\"Execute EJCalendar.py already\" >> $dailyScript
        echo fi >> $dailyScript
        chmod +x $dailyScript
    else
        echo No cron daily path: $cronDailyPath
    fi

    echo
fi

### Configure EJ Note Formatter ###
flag=$(GetConfigVar IsConfigureNoteFormatter $OS $VER)
AssertFunctionResult
if [ $flag = true ]
then
    echo Configure EJ Note Formatter

    if [ -d $cronDailyPath ]
    then
        noteFormatterCronScript=$(GetConfigVar LAMPNoteFormatterCronScript $OS $VER)
        AssertFunctionResult
        noteFormatterServicePath=$(GetConfigVar LAMPEJServicePath $OS $VER)
        AssertFunctionResult

        dailyScript=$cronDailyPath/$noteFormatterCronScript
        echo \#!/bin/bash > $dailyScript
        echo if [ -d $noteFormatterServicePath ]\; then >> $dailyScript
        echo "    "cd $noteFormatterServicePath >> $dailyScript
        echo "    echo "\"Sart Note Formatter handle script\" >> $dailyScript
        echo "    "if [ -f EJNoteFormatter.py ]\; then >> $dailyScript
        echo "        yestoday=\$(date \"+%Y-%m-%d\" -d \"-1 days\")" >> $dailyScript
        echo "        "python3 EJNoteFormatter.py format \\* \$yestoday>> $dailyScript
        echo "    "fi >> $dailyScript
        echo "    echo "\"Execute EJNoteFormatter.py already\" >> $dailyScript
        echo fi >> $dailyScript
        chmod +x $dailyScript
    else
        echo No cron daily path: $cronDailyPath
    fi

    echo
fi
